(function ($) {
    var g_maxFileSize = 1;
    /**
     * 自定义七牛云 文件上传
     * @param labelId 按钮id
     * @param targetId 文件值id
     * @param accept 文件过滤
     * @param maxFileSize 文件大小限制
     */
    $.zupfile = function (params) {
        var labelId = params.labelId;
        var targetId = params.targetId;
        var maxFileSize = params.maxFileSize || g_maxFileSize;
        maxFileSize = maxFileSize * 1024 * 1024;
        if (!labelId || !targetId) {
            return false;
        }
        var accept = params.accept || '';
        var fileInput = '<input type="file" style="display: none" id="file_' + labelId + '" accept="' + accept + '"/>';
        $("#" + labelId).append(fileInput);
        $("#file_" + labelId).on('change', function (e) {
            if (e.target.files.length <= 0) {
                return;
            }
            if (maxFileSize < e.target.files[0].size) {
                art.message('文件过大');
                return;
            }
            $("#" + labelId).showLoading();
            $.post(framework.base + '/admin/common/qiniu_token.json', {}, function (token) {
                var formData = new FormData();
                formData.append("token", token.token);
                formData.append("file", e.target.files[0]);
                var fileName = e.target.files[0].name;
                if (fileName.lastIndexOf(".") > 0) {
                    var fileExt = fileName.substring(fileName.lastIndexOf("."));
                    fileName = new Date().getTime() + fileExt;
                    formData.append("key", fileName);
                }
                $.ajax({
                    url: 'http://upload-z2.qiniup.com/', /*接口域名地址*/
                    type: 'post',
                    data: formData,
                    contentType: false,
                    processData: false,
                    success: function (res) {
                        if (res.state == 'SUCCESS') {
                            $("#" + targetId).val(res.source);
                            if (params.videoPre !== '') {
                                $("#" + params.videoPre).attr('src', res.source);
                            }
                        }
                    },
                    complete: function () {
                        $("#" + labelId).hideLoading();
                    }
                });
            });
        });
    }

    /**
     * 自定义七牛云 图片上传
     * @param labelId 按钮id
     * @param targetId 图片值 id
     * @param imgId 图片显示 id
     * @param accept 图片过滤
     * @param maxFileSize 文件大小限制
     */
    $.zupImg = function (params) {
        var labelId = params.labelId;
        var targetId = params.targetId;
        var imgId = params.imgId;
        var maxFileSize = params.maxFileSize || g_maxFileSize;
        maxFileSize = maxFileSize * 1024 * 1024;
        if (!labelId || !targetId) {
            return false;
        }
        var accept = params.accept || 'image/*';
        var fileInput = '<input type="file" style="display: none" id="file_' + labelId + '" accept="' + accept + '"/>';
        $("#" + labelId).append(fileInput);
        $("#file_" + labelId).on('change', function (e) {
            if (e.target.files.length <= 0) {
                return;
            }
            if (maxFileSize < e.target.files[0].size) {
                art.message('文件过大');
                return;
            }
            $("#" + labelId).showLoading();
            $.post(framework.base + '/admin/common/qiniu_token.json', {}, function (token) {
                var formData = new FormData();
                formData.append("token", token.token);
                formData.append("file", e.target.files[0]);
                var fileName = e.target.files[0].name;
                if (fileName.lastIndexOf(".") > 0) {
                    var fileExt = fileName.substring(fileName.lastIndexOf("."));
                    fileName = new Date().getTime() + fileExt;
                    formData.append("key", fileName);
                }
                $.ajax({
                    url: 'http://upload-z2.qiniup.com/', /*接口域名地址*/
                    type: 'post',
                    data: formData,
                    contentType: false,
                    processData: false,
                    success: function (res) {
                        if (res.state == 'SUCCESS') {
                            $("#" + targetId).val(res.source);
                            if (imgId) {
                                $("#" + imgId).attr("src", res.source);
                            }
                        }
                    },
                    complete: function () {
                        $("#" + labelId).hideLoading();
                    }
                });
            });
        });
    }

    /**
     * 自定义七牛云 图片上传
     * @param accept 图片过滤 默认image/*
     * @param mul 是否多图上传 默认false
     * @param init 单图上传时-初始图片路径
     * @param targetId 单图上传时-接收图片值 id
     * @param preview 多图上传时-是否预览 默认true
     * @param maxFileSize 文件大小限制
     */
    $.fn.zupImg = function (params) {
        var $upDiv = this;
        var accept = params.accept || 'image/*';
        var preview = params.preview;
        var maxFileSize = params.maxFileSize || g_maxFileSize;
        var imgClass = params.imgClass || "imgSpan";
        var maxFileNum = params.maxFileNum;

        maxFileSize = maxFileSize * 1024 * 1024;
        if (typeof (preview) == 'undefined') {
            preview = true;
        }

        //多图上传，最大图片数量限制
        if (params.mul && maxFileNum && maxFileNum>0) {
            this.addClass("img-box");
            var fileLabel = '<label class="disSortable">' +
                '<input type="file" style="display: none" multiple="multiple" accept="' + accept + '"/>' +
                '<span class="' + imgClass + '">+</span>' +
                '</label>';
            this.append(fileLabel);

            $upDiv.find("input[type=file]").on('change', function (e) {
                if (e.target.files.length <= 0) {
                    return;
                }
                var m_maxFileNum=maxFileNum;
                var currentFileNum=$(".img-box").children("div").length;
                if(currentFileNum && currentFileNum>0){
                    if(currentFileNum>=maxFileNum){
                        art.message('超出文件限定数量,最多'+maxFileNum+'张');
                        return;
                    }else{
                        if(currentFileNum+e.target.files.length>maxFileNum){
                            art.message('超出文件限定数量,最多'+maxFileNum+'张');
                        }
                        m_maxFileNum=maxFileNum-currentFileNum;
                    }

                }
                if (preview) {
                    for (var i = 0; i < e.target.files.length && i<m_maxFileNum; i++) {
                        if (maxFileSize < e.target.files[i].size) {
                            m_maxFileNum++;
                            art.message('文件过大');
                            continue;
                        }
                        var imgItem = '<div class="img-item">' +
                            '<img class="z_img" src="' + $.blogImg(e.target.files[i]) + '">' +
                            '<span class="img-remove iconfont icon-remove" onclick="$(this).parent().remove()"></span>' +
                            '</div>';
                        var $imgItem = $(imgItem);
                        $upDiv.find("label").before($imgItem);
                        $.data($imgItem.find("img")[0], "data-file", e.target.files[i]);
                    }
                } else {
                    $.post(framework.base + '/admin/common/qiniu_token.json', {}, function (token) {
                        for (var i = 0; i < e.target.files.length && i<m_maxFileNum; i++) {
                            if (maxFileSize < e.target.files[i].size) {
                                m_maxFileNum++;
                                art.message('文件过大');
                                continue;
                            }
                            var file = e.target.files[i];
                            var formData = new FormData();
                            formData.append("token", token.token);
                            formData.append("file", file);
                            var fileName = file.name;
                            if (fileName.lastIndexOf(".") > 0) {
                                var fileExt = fileName.substring(fileName.lastIndexOf("."));
                                fileName = new Date().getTime() + fileExt;
                                formData.append("key", fileName);
                            }
                            /* $(".img-box .disSortable").showLoading();*/
                            $.ajax({
                                url: 'http://upload-z2.qiniup.com/', /*接口域名地址*/
                                type: 'post',
                                data: formData,
                                contentType: false,
                                processData: false,
                                success: function (res) {
                                    if (res.state == 'SUCCESS') {
                                        var imgItem = '<div class="img-item">' +
                                            '<img class="z_img" src="' + res.source + '">' +
                                            '<span class="img-remove iconfont icon-remove" onclick="$(this).parent().remove()"></span>' +
                                            '</div>';
                                        var $imgItem = $(imgItem);
                                        $upDiv.find("label").before($imgItem);
                                    }
                                },
                                complete: function () {
                                    $(".img-box .disSortable").hideLoading();
                                }
                            });
                        }
                    });
                }
                if (preview && !$upDiv.find(".btn-upload")[0]) {
                    $upDiv.append('<a onclick="$.upImg(this);" class="btn btn-default btn-upload disSortable"><i class="glyphicon glyphicon-upload"></i>上传</a>');
                    e.target.value = '';
                }
                Sortable.create($upDiv[0], {filter: '.disSortable', animation: 150});
            });
            Sortable.create($upDiv[0], {filter: '.disSortable', animation: 150});
            return $upDiv;
        }

        //多图上传
        if (params.mul) {
            this.addClass("img-box");
            var fileLabel = '<label class="disSortable">' +
                '<input type="file" style="display: none" multiple="multiple" accept="' + accept + '"/>' +
                '<span class="' + imgClass + '">+</span>' +
                '</label>';
            this.append(fileLabel);

            $upDiv.find("input[type=file]").on('change', function (e) {
                if (e.target.files.length <= 0) {
                    return;
                }
                if (preview) {
                    for (var i = 0; i < e.target.files.length; i++) {
                        if (maxFileSize < e.target.files[i].size) {
                            continue;
                        }
                        var imgItem = '<div class="img-item">' +
                            '<img class="z_img" src="' + $.blogImg(e.target.files[i]) + '">' +
                            '<span class="img-remove iconfont icon-remove" onclick="$(this).parent().remove()"></span>' +
                            '</div>';
                        var $imgItem = $(imgItem);
                        $upDiv.find("label").before($imgItem);
                        $.data($imgItem.find("img")[0], "data-file", e.target.files[i]);
                    }
                } else {
                    $.post(framework.base + '/admin/common/qiniu_token.json', {}, function (token) {
                        for (var i = 0; i < e.target.files.length; i++) {
                            if (maxFileSize < e.target.files[i].size) {
                                continue;
                            }
                            var file = e.target.files[i];
                            var formData = new FormData();
                            formData.append("token", token.token);
                            formData.append("file", file);
                            var fileName = file.name;
                            if (fileName.lastIndexOf(".") > 0) {
                                var fileExt = fileName.substring(fileName.lastIndexOf("."));
                                fileName = new Date().getTime() + fileExt;
                                formData.append("key", fileName);
                            }
                            /* $(".img-box .disSortable").showLoading();*/
                            $.ajax({
                                url: 'http://upload-z2.qiniup.com/', /*接口域名地址*/
                                type: 'post',
                                data: formData,
                                contentType: false,
                                processData: false,
                                success: function (res) {
                                    if (res.state == 'SUCCESS') {
                                        var imgItem = '<div class="img-item">' +
                                            '<img class="z_img" src="' + res.source + '">' +
                                            '<span class="img-remove iconfont icon-remove" onclick="$(this).parent().remove()"></span>' +
                                            '</div>';
                                        var $imgItem = $(imgItem);
                                        $upDiv.find("label").before($imgItem);
                                    }
                                },
                                complete: function () {
                                    $(".img-box .disSortable").hideLoading();
                                }
                            });
                        }
                    });
                }
                if (preview && !$upDiv.find(".btn-upload")[0]) {
                    $upDiv.append('<a onclick="$.upImg(this);" class="btn btn-default btn-upload disSortable"><i class="glyphicon glyphicon-upload"></i>上传</a>');
                    e.target.value = '';
                }
                Sortable.create($upDiv[0], {filter: '.disSortable', animation: 150});
            });
            Sortable.create($upDiv[0], {filter: '.disSortable', animation: 150});
            return $upDiv;
        }

        //单图上传
        var img = "+";
        if (params.init) {
            img = '<img onerror=" this.src=\'' + framework.base + '/resources/img/img_default.png\' " src="' + params.init + '" style="width: 100%;max-height: 100%" />';
        }
        var fileLabel = '<label>' +
            '<input type="file" style="display: none" accept="' + accept + '"/>' +
            '<span class="' + imgClass + '"> ' + img + '</span>' +
            '</label>';
        $upDiv.append(fileLabel);

        $upDiv.find("input[type=file]").on('change', function (e) {
            if (e.target.files.length <= 0) {
                return;
            }
            if (maxFileSize < e.target.files[0].size) {
                return;
            }
            $upDiv.showLoading();
            $.post(framework.base + '/admin/common/qiniu_token.json', {}, function (token) {
                var formData = new FormData();
                formData.append("token", token.token);
                formData.append("file", e.target.files[0]);
                var fileName = e.target.files[0].name;
                if (fileName.lastIndexOf(".") > 0) {
                    var fileExt = fileName.substring(fileName.lastIndexOf("."));
                    fileName = new Date().getTime() + fileExt;
                    formData.append("key", fileName);
                }
                $.ajax({
                    url: 'http://upload-z2.qiniup.com/', /*接口域名地址*/
                    type: 'post',
                    data: formData,
                    contentType: false,
                    processData: false,
                    success: function (res) {
                        if (res.state == 'SUCCESS') {
                            $upDiv.find("." + imgClass).css("border", "0").html('<img style="width: 100%;max-height: 100%" src="' + res.source + '">');
                            if (params.targetId) {
                                $("#" + params.targetId).val(res.source);
                            }
                        }
                    },
                    complete: function () {
                        $upDiv.hideLoading();
                    }
                });
            });
        });
        return $upDiv;
    }

    $.blogImg = function (file) {
        window.URL = window.URL || window.webkitURL;
        return window.URL.createObjectURL(file);
    }

    $.upImg = function (node) {
        var imgList = $(node).parent().find(".z_img");
        $.post(framework.base + '/admin/common/qiniu_token.json', {}, function (token) {
            $.each(imgList, function (index) {
                var $img = $(this);
                var file = $.data($img[0], "data-file");
                var formData = new FormData();
                formData.append("token", token.token);
                formData.append("file", file);
                var fileName = file.name;
                if (fileName.lastIndexOf(".") > 0) {
                    var fileExt = fileName.substring(fileName.lastIndexOf("."));
                    fileName = new Date().getTime() + fileExt;
                    formData.append("key", fileName);
                }
                $img.showLoading();
                $.ajax({
                    url: 'http://upload-z2.qiniup.com/', /*接口域名地址*/
                    type: 'post',
                    data: formData,
                    contentType: false,
                    processData: false,
                    success: function (res) {
                        if (res.state == 'SUCCESS') {
                            $img.attr("src", res.source);
                            $img.next().removeClass("icon-remove").addClass("icon-ok");
                        }
                    },
                    complete: function () {
                        $img.hideLoading();
                    }
                });
            })
            $(node).hide();
            $(node).prev().hide();
        });
    }
    $.fn.getImgs = function () {
        var imgList = [];
        $.each(this.find(".z_img"), function (index) {
            imgList.push($(this).attr("src"));
        });
        return imgList;
    }
    $.fn.addImg = function (img) {
        var imgItem = '<div class="img-item">' +
            '<img class="z_img" src="' + img + '">' +
            '<span class="img-remove iconfont icon-remove" onclick="$(this).parent().remove()"></span>' +
            '</div>';
        this.find(".disSortable").before(imgItem);
        //this.prepend(imgItem);
    }
})(jQuery);